/**
 * 
 */
package com.hector.meinewerk.client.view.common;

import java.util.ArrayList;
import java.util.ListIterator;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hector.meinewerk.client.R;
import com.hector.meinewerk.client.view.widget.adapter.CatergoryView;
import com.hector.meinewerk.client.view.widget.adapter.ProductAdapter;
import com.hector.meinewerk.common.ActionEvent;
import com.hector.meinewerk.common.ActionEventConstant;
import com.hector.meinewerk.common.BaseActivity;
import com.hector.meinewerk.common.MeineWerkApplication;
import com.hector.meinewerk.common.ModelEvent;
import com.hector.meinewerk.common.ServerPath;
import com.hector.meinewerk.controller.UserController;
import com.hector.meinewerk.model.Category;
import com.hector.meinewerk.model.Product;
import com.hector.meinewerk.utils.ImageLoader;
import com.hector.meinewerk.utils.StringUtil;

public class MainView extends BaseActivity implements OnClickListener {
	private static final int MIN_ROW = 5;
	private static final int MAX_ITEM = 10;
	private static final int SCREEN_CATEGORIES_ROOT = 0;
	private static final int SCREEN_CATEGORIES_PARENT = 1;
	private static final int SCREEN_PRODUCT = 2;

	// Variable
	private static final String TAG = "MainView";
	private ArrayList<Category> mCategoriesTree = new ArrayList<Category>();
	private ArrayList<Category> mCategories = new ArrayList<Category>();
	private Category mCategoryParent = new Category();
	private Category mCategoryProduct = new Category();
	private String mCurrentCategoryId;
	private int mCurrentScreen = SCREEN_CATEGORIES_ROOT;
	private boolean mIsLoadingMore = false;
	private boolean mHasMoreProducts = true;
	private int mCurrentOffset = 0;

	// View
	private ListView mListViewProduct;
	private ProductAdapter mProductAdapter;
	private ViewGroup mLayoutCatergories;
	private TextView mTxtTitleCategory;
	private HorizontalScrollView hscroll_catergories;
	private View mFooterView;

	// image view button back
	ImageView ivBack;
	// image view button home
	ImageView ivSetting;
	// image view button setting
	ImageView ivHome;

	RelativeLayout rlBottom;
	Button btButton1;
	Button btButton2;
	Button btButton3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product);
		setupViews();
		// requestGetCatergories();
		requestGetCategoryTree();
	}

	private void setupViews() {
		mListViewProduct = (ListView) findViewById(R.id.list_product);
		mLayoutCatergories = (LinearLayout) findViewById(R.id.layout_catergories);
		mTxtTitleCategory = (TextView) findViewById(R.id.txt_title_category);
		hscroll_catergories = (HorizontalScrollView) findViewById(R.id.hscroll_catergories);

		ivBack = (ImageView) this.findViewById(R.id.ivBack);
		ivBack.setOnClickListener(this);
		ivHome = (ImageView) this.findViewById(R.id.ivHome);
		ivHome.setOnClickListener(this);
		ivSetting = (ImageView) this.findViewById(R.id.ivSetting);
		ivSetting.setOnClickListener(this);

		mProductAdapter = new ProductAdapter(mActivity);
		mListViewProduct.setAdapter(mProductAdapter);
		mListViewProduct.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// what is the bottom iten that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;

				// is the bottom item visible & not loading more already ? Load
				// more !
				if ((lastInScreen == totalItemCount) && !(mIsLoadingMore)) {
					if ((getCurrentScreen() == SCREEN_CATEGORIES_PARENT || getCurrentScreen() == SCREEN_PRODUCT)
							&& !TextUtils.isEmpty(mCurrentCategoryId)
							&& mHasMoreProducts) {
						Log.v(TAG, "gggggggggggggg");
						mIsLoadingMore = true;
						mCurrentOffset++;
						if (mListViewProduct.getFooterViewsCount() > 0) {
							mListViewProduct.addFooterView(mFooterView);
						}
						requestGetCatergory(mCurrentCategoryId, mCurrentOffset);
					}

				}
			}
		});

		// add the footer before adding the adapter, else the footer will nod
		// load!
		mFooterView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.footer_loading_more, null, false);

		rlBottom = (RelativeLayout) this.findViewById(R.id.rlBottom);
		btButton1 = (Button) this.findViewById(R.id.btButton1);
		btButton1.setOnClickListener(this);
		btButton2 = (Button) this.findViewById(R.id.btButton2);
		btButton2.setOnClickListener(this);
		btButton3 = (Button) this.findViewById(R.id.btButton3);
		btButton3.setOnClickListener(this);
	}

	private int getItemPerRow() {
		return MeineWerkApplication.getWidthScreen()
				/ MeineWerkApplication.convertDensityToPixel(mContext, 90);
	}

	private void updateUI() {
		// if(!mIsLoadingMore && mListViewProduct.getFooterViewsCount() > 0){
		// mListViewProduct.removeFooterView(mFooterView);
		// }
		switch (mCurrentScreen) {
		case SCREEN_CATEGORIES_ROOT:
			ivBack.setVisibility(View.INVISIBLE);
			mTxtTitleCategory.setText("Root");
			mProductAdapter = new ProductAdapter(mActivity);
			mListViewProduct.setAdapter(mProductAdapter);
			setupCatergories(mCategoriesTree);
			break;
		case SCREEN_CATEGORIES_PARENT:
			ivBack.setVisibility(View.VISIBLE);
			mTxtTitleCategory.setText(mCategoryParent.getName());
			if (!mIsLoadingMore) {
				mProductAdapter = new ProductAdapter(mActivity);
				mProductAdapter.setProducts(mCategoryParent.getProducts());
				mListViewProduct.setAdapter(mProductAdapter);
			} else {
				// final ArrayList<Product> products = new ArrayList<Product>();
				// products.addAll(mCategoryParent.getProducts());
				// for (int i = 0; i < getItemPerRow() * MIN_ROW; i++) {
				// products.add(new Product());
				// }
				// mCategoryParent.setProducts(products);
				mProductAdapter.setProducts(mCategoryParent.getProducts());
				mProductAdapter.notifyDataSetChanged();
			}
			setupCatergories(mCategories);
			break;
		case SCREEN_PRODUCT:
			ivBack.setVisibility(View.VISIBLE);
			setupCatergories(new ArrayList<Category>());
			if (!mIsLoadingMore) {
				mProductAdapter = new ProductAdapter(mActivity);
				mProductAdapter.setProducts(mCategoryProduct.getProducts());
				mListViewProduct.setAdapter(mProductAdapter);
			} else {
				// final ArrayList<Product> products = new ArrayList<Product>();
				// products.addAll(mCategoryProduct.getProducts());
				// for (int i = 0; i < getItemPerRow() * MIN_ROW; i++) {
				// products.add(new Product());
				// }
				// mCategoryProduct.setProducts(products);
				mProductAdapter.setProducts(mCategoryProduct.getProducts());
				mProductAdapter.notifyDataSetChanged();
			}
			// mProductAdapter = new ProductAdapter(mActivity);
			// mP+ctAdapter.notifyDataSetChanged();
			// mListViewProduct.setAdapter(mProductAdapter);
			mTxtTitleCategory.setText(mCategoryProduct.getName());
			break;
		}
	}

	private void setupCatergories(ArrayList<Category> categories) {
		if (categories == null)
			return;

		mLayoutCatergories.removeAllViews();
		for (Category category : categories) {
			final CatergoryView view = new CatergoryView(mActivity, category);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Category category = (Category) v.getTag();
					mCurrentCategoryId = category.getId();
					if (getCurrentScreen() == SCREEN_CATEGORIES_ROOT) {
						mCategories = category.getChildCategories();
					}
					setupCatergories(category.getChildCategories());
					requestGetCatergory(category.getId(), 0);
				}
			});
			mLayoutCatergories.addView(view, params);
		}
		if (categories.size() <= 0) {
			hscroll_catergories.setVisibility(View.GONE);
		} else {
			hscroll_catergories.setVisibility(View.VISIBLE);
		}
	}

	private void requestGetCategoryTree() {
		this.showProgressDialog(StringUtil.getString(R.string.LOADING));
		ArrayList<String> data = new ArrayList<String>();

		ActionEvent event = new ActionEvent();
		event.action = ActionEventConstant.REQUEST_CATERGORIES_TREE;
		event.userData = data;
		event.sender = this;

		UserController.getInstance().handleViewEvent(event);
	}

	private void requestGetCatergory(String catergoryId, int offset) {
		this.showProgressDialog(StringUtil.getString(R.string.LOADING));
		ArrayList<String> data = new ArrayList<String>();
		data.add(catergoryId);
		data.add(MAX_ITEM + "");
		data.add(String.valueOf(offset));

		ActionEvent event = new ActionEvent();
		event.action = ActionEventConstant.REQUEST_CATERGORY;
		event.userData = data;
		event.sender = this;

		UserController.getInstance().handleViewEvent(event);
	}

	private void setCurrentScreen(int screen) {
		mCurrentScreen = screen;
	}

	private int getCurrentScreen() {
		return mCurrentScreen;
	}

	/*
	 * xu ly cac su kien hoan thanh nhan tu controller
	 * 
	 * @see
	 * com.hector.meinewerk.common.BaseActivity#handleModelViewEvent(com.hector
	 * .meinewerk.common.ModelEvent)
	 */
	@Override
	public void handleModelViewEvent(ModelEvent modelEvent) {
		Log.v(TAG, "modelMessageSuccess: " + modelEvent.getModelMessage());
		ActionEvent event = modelEvent.getActionEvent();
		switch (event.action) {
		case ActionEventConstant.REQUEST_CATERGORIES_TREE:
			final ArrayList<Category> treeCatergories = (ArrayList<Category>) modelEvent
					.getModelData();
			if (treeCatergories != null) {
				mCategoriesTree = treeCatergories;
				setCurrentScreen(SCREEN_CATEGORIES_ROOT);
				updateUI();
			}

			this.closeProgressDialog();
			break;
		case ActionEventConstant.REQUEST_CATERGORY:
			final Category category = (Category) modelEvent.getModelData();
			if (!mIsLoadingMore) {
				if (getCurrentScreen() == SCREEN_CATEGORIES_ROOT) {
					setCurrentScreen(SCREEN_CATEGORIES_PARENT);
					mCategoryParent = category;
					mHasMoreProducts = true;
				} else {
					setCurrentScreen(SCREEN_PRODUCT);
					mCategoryProduct = category;
					mHasMoreProducts = true;
				}

			} else {
				if (getCurrentScreen() == SCREEN_CATEGORIES_PARENT) {
					if (mCategoryParent.getProducts() == null) {
						mCategoryParent = category;
					} else {
						ListIterator<Product> listIterator = mCategoryParent
								.getProducts().listIterator();
						while (listIterator.hasNext()) {
							if (listIterator.next().getId() == null) {
								listIterator.remove();
							}
						}

						final ArrayList<Product> products = new ArrayList<Product>();
						products.addAll(mCategoryParent.getProducts());
						products.addAll(category.getProducts());

						if (products.size() >= getItemPerRow() * MIN_ROW) {
							final int modProduct = products.size()
									% getItemPerRow();
							if (modProduct != 0) {
								for (int i = 0; i < (getItemPerRow() - modProduct); i++) {
									products.add(new Product());
								}
							}
						} else {
							final int remainProduct = getItemPerRow() * MIN_ROW
									- products.size();
							for (int i = 0; i < remainProduct; i++) {
								products.add(new Product());
							}
						}
						mCategoryParent.setProducts(products);
					}
				} else if (getCurrentScreen() == SCREEN_PRODUCT) {
					if (mCategoryProduct.getProducts() == null) {
						mCategoryProduct = category;
					} else {
						ListIterator<Product> listIterator = mCategoryProduct
								.getProducts().listIterator();
						while (listIterator.hasNext()) {
							if (listIterator.next().getId() == null) {
								listIterator.remove();
							}
						}

						final ArrayList<Product> products = new ArrayList<Product>();
						products.addAll(mCategoryProduct.getProducts());
						products.addAll(category.getProducts());

						if (products.size() >= getItemPerRow() * MIN_ROW) {
							final int modProduct = products.size()
									% getItemPerRow();
							if (modProduct != 0) {
								for (int i = 0; i < (getItemPerRow() - modProduct); i++) {
									products.add(new Product());
								}
							}
						} else {
							final int remainProduct = getItemPerRow() * MIN_ROW
									- products.size();
							for (int i = 0; i < remainProduct; i++) {
								products.add(new Product());
							}
						}

						mCategoryProduct.setProducts(products);
					}
				}
			}

			if (category.getProducts().size() < MAX_ITEM) {
				mHasMoreProducts = false;
			}

			updateUI();

			mIsLoadingMore = false;
			this.closeProgressDialog();
			break;

		// case ActionEventConstant.REQUEST_CATERGORIES:
		// this.closeProgressDialog();
		//
		// final ArrayList<Category> catergories = (ArrayList<Category>)
		// modelEvent
		// .getModelData();
		// if (catergories != null) {
		// mCategories = catergories;
		// setupCatergories(mCategories);
		// }
		// break;
		// case ActionEventConstant.REQUEST_PRODUCT:
		// final Product product = (Product) modelEvent.getModelData();
		// this.closeProgressDialog();
		// break;
		//
		// default:
		// super.handleModelViewEvent(modelEvent);
		// break;
		}
	}

	/*
	 * Xu ly cac su kien loi nhan tu controller
	 * 
	 * @see
	 * com.hector.meinewerk.common.BaseActivity#handleErrorModelViewEvent(com
	 * .hector.meinewerk.common.ModelEvent)
	 */
	@Override
	public void handleErrorModelViewEvent(ModelEvent modelEvent) {
		super.handleErrorModelViewEvent(modelEvent);
		Log.v(TAG, "modelMessageError: " + modelEvent.getModelMessage());
		this.closeProgressDialog();

		ActionEvent event = modelEvent.getActionEvent();
		switch (event.action) {
		case ActionEventConstant.REQUEST_CATERGORY:
			mIsLoadingMore = false;
			mListViewProduct.removeFooterView(mFooterView);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		mCurrentScreen--;
		mCurrentOffset = 0;
		if (mCurrentScreen < 0) {
			super.onBackPressed();
		} else {
			updateUI();
		}
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
		ImageLoader.stopThread();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (arg0 == ivBack) {
			mCurrentOffset = 0;
			mCurrentScreen--;
			updateUI();
		} else if (arg0 == ivHome) {
			this.gotoMeineWerkAdmin();
		} else if (arg0 == ivSetting) {

		} else if (arg0 == btButton1) {
			showScreenButton1();
		} else if (arg0 == btButton2) {
			showScreenButton2();
		} else if (arg0 == btButton3) {
			showScreenButton3();
		}
	}

	public void showScreenButton1() {
		ActionEvent event = new ActionEvent();
		event.action = ActionEventConstant.SHOW_SCREEN_1;
		event.viewData = new Bundle();
		event.sender = this;
		UserController.getInstance().handleViewEvent(event);
	}

	public void showScreenButton2() {
		ActionEvent event = new ActionEvent();
		event.action = ActionEventConstant.SHOW_SCREEN_2;
		event.viewData = new Bundle();
		event.sender = this;
		UserController.getInstance().handleViewEvent(event);
	}

	public void showScreenButton3() {
		ActionEvent event = new ActionEvent();
		event.action = ActionEventConstant.SHOW_SCREEN_3;
		event.viewData = new Bundle();
		event.sender = this;
		UserController.getInstance().handleViewEvent(event);
	}

	/**
	 * 
	 * display application meine werk admin
	 * 
	 * @author: HaiTC3
	 * @return: void
	 * @throws:
	 * @since: Mar 11, 2013
	 */
	public void gotoMeineWerkAdmin() {
		boolean checkExist = false;
		try {
			ApplicationInfo info = getPackageManager().getApplicationInfo(
					ServerPath.PACKAGE_APP_VER_ADMIN, 0);
			checkExist = true;
		} catch (PackageManager.NameNotFoundException e) {
			checkExist = false;
		}

		if (checkExist) {
			Intent i = new Intent();
			PackageManager manager = getPackageManager();
			i = manager
					.getLaunchIntentForPackage(ServerPath.PACKAGE_APP_VER_ADMIN);
			i.addCategory(Intent.CATEGORY_LAUNCHER);
			startActivity(i);
		} else {
			this.showDialog(StringUtil
					.getString(R.string.TEXT_NOTIFY_PACKAGE_NO_EXIST));
		}
	}
	// private void requestGetCatergories() {
	// String parentID = 0 + "";
	//
	// this.showProgressDialog(StringUtil.getString(R.string.LOADING));
	// ArrayList<String> data = new ArrayList<String>();
	// data.add(parentID);
	// data.add(10 + "");
	// data.add(0 + "");
	//
	// ActionEvent event = new ActionEvent();
	// event.action = ActionEventConstant.REQUEST_CATERGORIES;
	// event.userData = data;
	// event.sender = this;
	//
	// UserController.getInstance().handleViewEvent(event);
	// }

	// private void requestGetProduct() {
	// String catergoryId = String.valueOf(46);
	//
	// this.showProgressDialog(StringUtil.getString(R.string.LOADING));
	// ArrayList<String> data = new ArrayList<String>();
	// data.add(catergoryId);
	//
	// ActionEvent event = new ActionEvent();
	// event.action = ActionEventConstant.REQUEST_PRODUCT;
	// event.userData = data;
	// event.sender = this;
	//
	// UserController.getInstance().handleViewEvent(event);
	// }
}
